package com.bigdata.hbase_mr.write;

import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/*
KEYIN,VALUEIN: reduce 接收并处理的数据类型, 以每个单词为一组来处理
KEYOUT,VALUEOUT: 单词出现的次数，key -> word，value -> count;
 */
public class ClazzReducer extends TableReducer<Text, IntWritable, ImmutableBytesWritable> {
    private IntWritable result = new IntWritable();


    public static void main(String[] args) {
        String rowKey = MD5Hash.digest("文科一班").toString();
        System.out.println(rowKey);
    }


    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, ImmutableBytesWritable, Mutation>.Context context) throws IOException, InterruptedException {

        int sum = 0;
        Iterator<IntWritable> iterator = values.iterator();
        while (iterator.hasNext()) {
            // 等同于下面的遍历效果
            IntWritable value = iterator.next();
            sum += value.get();
        }

        String rowKey = MD5Hash.digest(key.toString()).toString();

        Put put = new Put(rowKey.getBytes());
        put.addColumn("cf".getBytes(), "name".getBytes(), key.toString().getBytes());
        put.addColumn("cf".getBytes(), "count".getBytes(), String.valueOf(sum).getBytes());
        context.write(null, put);

    }
}
